#pragma once
#include "../comm/logger.hpp"
#include "../comm/util.hpp"
#include <unordered_map>
#include <cassert>
namespace ns_model
{
    using namespace std;
    using namespace ns_util;
    struct Question
    {
        std::string number; // 题目编号，唯一
        std::string title;  // 题目的标题
        std::string star;   // 难度: 简单 中等 困难
        int cpu_limit;      // 题目的时间要求(S)
        int mem_limit;      // 题目的空间要去(KB)
        std::string desc;   // 题目的描述
        std::string header; // 题目预设给用户在线编辑器的代码
        std::string tail;   // 题目的测试用例，需要和header拼接，形成完整代码
    };
    const string question_list = "./questions/questions.list";
    const std::string questins_path = "./questions/";

    class Model
    {
    public:
        Model()
        {
            assert(LoadQuestionList(question_list));
        }
        ~Model() {}

        bool LoadQuestionList(const string &question_list)
        {
            // 1.加载配置文件
            ifstream in(question_list);
            if (!in.is_open())
            {
                LOG(FATAL, "加载题库失败，请检查文件路径是否正确\n");
                return false;
            }

            string line;
            while (getline(in, line))
            {
                std::vector<std::string> tokens;

                // 1 判断回文数 简单 1 30000
                StringUtil::SplitString(line, &tokens, " ");

                if (tokens.size() != 5)
                {
                    continue;
                }

                // 2.1 填充题目字段
                Question q;
                q.number = tokens[0];
                q.title = tokens[1];
                q.star = tokens[2];
                q.cpu_limit = atoi(tokens[3].c_str());
                q.mem_limit = atoi(tokens[4].c_str());

                string path = questins_path + q.number + "/";

                // 2.2 读取文件数据
                FileUtil::ReadFile(path + "desc.txt", &(q.desc), true);
                FileUtil::ReadFile(path + "header.cpp", &(q.header), true);
                FileUtil::ReadFile(path + "tail.cpp", &(q.tail), true);

                // 3.插入questions

                quesions.insert({q.number, q});
            }

            LOG(INFO,"加载题库...成功!\n");
            in.close();

            return true;
        }

        bool GetAllQuestions(vector<Question> *out)
        {
            if (quesions.empty())
            {
                LOG(ERROR, "用户获取题库失败\n");
            }

            for (const auto &quesion : quesions)
            {
                out->emplace_back(quesion.second);
            }
            return true;
        }

        bool GetOneQuestion(const std::string &number, Question *q)
        {
            auto it = quesions.find(number);
            if (it == quesions.end())
            {
                LOG(ERROR, "获取题目失败\n");
                return false;
            }
            (*q) = it->second;
            return true;
        }

    private:
        unordered_map<string, Question> quesions;
    };
}